/**
 * Copyright (C) 2013 Inera AB (http://www.inera.se)
 *
 * This file is part of Inera Certificate Proxy (http://code.google.com/p/inera-certificate-proxy).
 *
 * Inera Certificate Proxy is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Inera Certificate Proxy is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package se.inera.certificate.proxy.mappings;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;

public class MapperImpl implements Mapper {

    private Logger log = LoggerFactory.getLogger(MapperImpl.class);

    private List<Mapping> mappings = newArrayList();

    public MapperImpl() {
        // EMPTY
    }

    public Mapping getMapping(String path) {
        checkNotNull(path, "path is null!");

        for (Mapping m : mappings) {
            if (path.startsWith(m.getContext())) {
                log.debug("CHECK [{}] >>> [{}] (OK)", path, m.getContext());
                return m;
            }
            log.debug("CHECK [{}] >>> [{}] (NOK)", path, m.getContext());
        }
        return null;
    }

    public void setMappings(Map<String, String> mappings) {
        checkNotNull(mappings, "mappings is null!");
        checkArgument(!mappings.isEmpty(), "mappings is empty!");

        this.mappings.clear();
        for (Map.Entry<String, String> entry :  mappings.entrySet()) {
            checkNotNull(entry.getKey(), "key in mappings entry is null!");
            checkNotNull(entry.getValue(), "value in mappings entry is null!");

            Mapping mapping = MappingFactory.create(entry.getKey(), entry.getValue());
            this.mappings.add(mapping);
            log.info("MAPPING: {}", mapping);
        }
    }
}
